package com.boarsoft.boar.code.mac.flow.action;

import javax.servlet.http.HttpServletRequest;

import com.boarsoft.common.dao.PagedResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.boarsoft.bean.ReplyInfo;
import com.boarsoft.boar.code.agent.service.CodeService;
import com.boarsoft.boar.code.entity.ProHandlerInfo;
import com.boarsoft.boar.code.mac.flow.biz.ProcessHandlerInfoBiz;
import com.boarsoft.boar.code.mac.flow.generator.ProcessHandlerGenerator;
import com.boarsoft.boar.context.ActionContext;
import com.boarsoft.common.Util;
import com.boarsoft.rpc.core.RpcContext;

/**
 * 流程图服务
 *
 * @author Mac_J
 */
@RestController
@RequestMapping("/mac/flow/process")
public class ProcessAction {
	private Logger log = LoggerFactory.getLogger(WrapAction.class);

	@Autowired
	private ProcessHandlerInfoBiz processHandlerInfoBiz;

	@Autowired
	private ProcessHandlerGenerator processHandlerGenerator;

	@Autowired
	@Qualifier("developerCodeService")
	private CodeService developerCodeService;

	@RequestMapping("/save.do")
	// @Authorized(code = "flow.save")
	public ReplyInfo<Object> save(ProHandlerInfo proHandlerInfo) {
		return new ReplyInfo<Object>(true, processHandlerInfoBiz.add(proHandlerInfo));
	}

	@RequestMapping("/get.do")
	public ReplyInfo<Object> get(String type, String faceId, String faceCode, String methodId, String methodCode, String id,
			String code) {
		return ReplyInfo.SUCCESS;
	}

	@RequestMapping("/list.do")
	public ReplyInfo<Object> list(String appId, String faceId, String key, String orderBy, int pageNo, int pageSize) {
		PagedResult<ProHandlerInfo> pr = processHandlerInfoBiz.list(appId, faceId, key, orderBy, pageNo, pageSize);
		return new ReplyInfo<Object>(true, pr);
	}

	@RequestMapping("/submit.do")
	public ReplyInfo<Object> submit(String type, String code, String appId, String projCode, HttpServletRequest request) {
		String ip = ActionContext.getRemoteIp(request);
		if (Util.strIsEmpty(ip)) {
			return new ReplyInfo<Object>("Can not get IP");
		}
		RpcContext.specify2(ip.concat(":9941"));
		try {
			String java = processHandlerGenerator.generate(code, appId);
			try {
				developerCodeService.write(projCode, code, java);
			} catch (Throwable e) {
				log.error("Can not write java source to remote server", e);
			}
			return new ReplyInfo<>(true, java);
		} catch (Throwable e) {
			log.error("Error on generate code", e);
			return new ReplyInfo<Object>(e.getMessage());
		} finally {
			RpcContext.specify2(null);
		}
	}
}